package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.util.GuoYangYun;
import com.itheima.health.util.ValidateCodeUtils;
import com.itheima.health.util.YanZheng;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 验证码Controller
 */
@RestController
@RequestMapping("/mobile/validateCode")
@Slf4j
@Api(tags = "手机端验证码接口")
public class MobileValidateCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取验证码
     * @param type
     * @param telephone
     * @return
     */
    @PostMapping("/send")
    public Result sendCodeToLogin(String type, String telephone){
        // 使用工具类获取随机四位数验证码
        YanZheng.send(telephone,type);
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("生成的登录验证码：{}", code);
        // 使用redis对象操作字符串类型数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 设置key为telephone的验证码code存活时间为60秒
        valueOperations.set("telephone", code,2,TimeUnit.MINUTES);
        GuoYangYun.sendMsg(telephone, code+"");
        return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
    }

}
